package com.lic.license.param;

import de.schlichtherle.license.AbstractKeyStoreParam;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 自定义KeyStoreParam，用于将公私钥存储文件存放到其他磁盘位置而不是项目中
 */
public class CustomKeyStoreParam extends AbstractKeyStoreParam {

    /**
     * 公钥/私钥在磁盘上的存储路径
     */
    private String storePath;
    private String alias;
    private String storePwd;
    private String keyPwd;

    public CustomKeyStoreParam(Class clazz, String resource, String alias, String storePwd, String keyPwd) {
        super(clazz, resource);
        this.storePath = resource;
        this.alias = alias;
        this.storePwd = storePwd;
        this.keyPwd = keyPwd;
    }

    @Override
    public String getAlias() {
        return alias;
    }

    @Override
    public String getStorePwd() {
        return storePwd;
    }

    @Override
    public String getKeyPwd() {
        return keyPwd;
    }


    /**
     * 复写de.schlichtherle.license.AbstractKeyStoreParam的getStream()方法<br/>
     *  默认先从项目路径下获取公钥文件,如果文件为在磁盘的其他路径下面,将从该路径下获取文件
     */
    @Override
    public  InputStream getStream() throws IOException {
        InputStream in;
        File file;

        ClassPathResource classPathResource = new ClassPathResource(storePath);
        if(!classPathResource.exists()){
            file = ResourceUtils.getFile(storePath);
            if(!file.exists()){
                file = new File(storePath);
            }
            in = new FileInputStream(file);
        }else {
            in = classPathResource.getInputStream();
        }
        return in;
    }
}
